package nc.bs.bd.pfxx.plugin;

import java.util.*;

import nc.bs.dao.BaseDAO;
import nc.bs.dao.DAOException;
import nc.bs.framework.common.NCLocator;
import nc.bs.logging.Logger;
import nc.bs.pfxx.ISwapContext;
import nc.bs.pfxx.plugin.AbstractPfxxPlugin;
import nc.bs.trade.business.HYPubBO;
import nc.itf.bd.material.assign.IMaterialAssignService;
import nc.itf.bd.material.baseinfo.IMaterialBaseInfoService;
import nc.itf.bd.material.measdoc.IMeasdocService;
import nc.vo.bd.errorlog.ErrLogReturnValue;
import nc.vo.bd.errorlog.ErrorMsgVO;
import nc.vo.bd.material.MaterialConvertVO;
import nc.vo.bd.material.MaterialTaxTypeVO;
import nc.vo.bd.material.MaterialVO;
import nc.vo.bd.material.measdoc.MeasdocVO;
import nc.vo.corg.CostRegionVO;
import nc.vo.ml.NCLangRes4VoTransl;
import nc.vo.pfxx.auxiliary.AggxsysregisterVO;
import nc.vo.pfxx.util.PfxxPluginUtils;
import nc.vo.pub.BusinessException;
import nc.vo.pub.lang.UFBoolean;
import nccloud.commons.lang.StringUtils;


public class MaterialPfxxPlugin
        extends AbstractPfxxPlugin {
    private BaseDAO baseDAO = null;

    private IMaterialBaseInfoService service = null;
    private IMeasdocService iMeasdocService;

    protected Object processBill(Object vo, ISwapContext swapContext, AggxsysregisterVO aggxsysvo) throws BusinessException {
        String pk = null;
        try {
            MaterialVO materialVO = (MaterialVO) vo;
            String sender = swapContext.getSender();
            if("TT".equalsIgnoreCase(sender)){// 非生产厂商档案
                // manufacturer
                Object manufacturer = materialVO.getAttributeValue("manufacturer");
                if (manufacturer != null && !manufacturer.toString().isEmpty()){
                    materialVO.setAttributeValue("def10", manufacturer);
                    materialVO.setAttributeValue("manufacturer", null);
                }
            }

            //外层pk_measdoc
            if (materialVO.getPk_measdoc() == null && materialVO.getPk_measdoc().isEmpty()) {
                return "Pk_measdoc为空";
            }
            Collection<MeasdocVO> collection = getBaseDAO().retrieveByClause(MeasdocVO.class, " name = '" + materialVO.getPk_measdoc() + "'");

            MeasdocVO measdocVO = new MeasdocVO();
            if (collection.size() != 0) {
                MeasdocVO measdocVO01 = (MeasdocVO) collection.iterator().next();
                materialVO.setAttributeValue("pk_measdoc", measdocVO01.getPk_measdoc());
            } else {
                //10mM*1ml
                measdocVO.setAttributeValue("code", materialVO.getPk_measdoc());  //计量基本单位
                measdocVO.setAttributeValue("name", materialVO.getPk_measdoc());  //计量单位名称
                measdocVO.setAttributeValue("pk_org", materialVO.getPk_org());   //所属组织
                measdocVO.setAttributeValue("oppdimen", "E");      //所属量纲
                measdocVO.setAttributeValue("basecodeflag", new UFBoolean(false));  //是否基本单位
                measdocVO.setAttributeValue("bitnumber", 4);
                measdocVO.setAttributeValue("pk_group", materialVO.getPk_group());
                measdocVO.setAttributeValue("scalefactor", 1.00000000);    //换算系数
                System.out.println("measdocVO==========" + measdocVO);
                getIMeasdocService().insertMeasdocForPfxx(measdocVO);
                materialVO.setAttributeValue("pk_measdoc", measdocVO.getPk_measdoc());
                System.out.println("=========================================");
            }

//         MaterialVO materialVO2 = (MaterialVO)vo;
            String pkMeasdoc = materialVO.getPk_measdoc();
            //内层pk_measdoc
            if (materialVO.getMaterialconvert() != null) {
                MaterialConvertVO[] materialconvert = materialVO.getMaterialconvert();
                if (materialconvert != null) {
                    for (MaterialConvertVO convertVO : materialconvert) {
                        String pkMeasdocs = convertVO.getPk_measdoc();
                        if (!pkMeasdocs.equals(pkMeasdoc)) {
                            Collection<MeasdocVO> collection2 = getBaseDAO().retrieveByClause(MeasdocVO.class, " name = '" + pkMeasdocs + "'");

                            MeasdocVO measdocVO2 = new MeasdocVO();
                            if (collection2.size() != 0) {
                                MeasdocVO measdocVO02 = (MeasdocVO) collection2.iterator().next();
//                             materialVO.setAttributeValue("pk_measdoc",measdocVO02.getPk_measdoc());
                                convertVO.setAttributeValue("pk_measdoc", measdocVO02.getPk_measdoc());
                            } else {
                                //10mM*1ml
                                measdocVO2.setAttributeValue("code", pkMeasdocs);  //计量基本单位
                                measdocVO2.setAttributeValue("name", pkMeasdocs);  //计量单位名称
                                measdocVO2.setAttributeValue("pk_org", materialVO.getPk_org());   //所属组织
                                measdocVO2.setAttributeValue("oppdimen", "E");      //所属量纲
                                measdocVO2.setAttributeValue("basecodeflag", new UFBoolean(false));  //是否基本单位
                                measdocVO2.setAttributeValue("bitnumber", 4);
                                measdocVO2.setAttributeValue("pk_group", materialVO.getPk_group());
                                measdocVO2.setAttributeValue("scalefactor", 1.00000000);    //换算系数
                                System.out.println("measdocVO==========" + measdocVO2);
                                getIMeasdocService().insertMeasdocForPfxx(measdocVO2);
//                             materialVO.setAttributeValue("pk_measdoc", measdocVO2.getPk_measdoc());
                                convertVO.setAttributeValue("pk_measdoc", measdocVO2.getPk_measdoc());
                                System.out.println("=========================================");
                            }
                        }
                    }
                }
            }
            pk = PfxxPluginUtils.queryBillPKBeforeSaveOrUpdate(swapContext.getBilltype(), swapContext.getDocID());
            if (StringUtils.isBlank(pk)) {
                materialVO = insertMaterialVO(materialVO);
                PfxxPluginUtils.addDocIDVsPKContrast(swapContext.getBilltype(), swapContext.getDocID(), materialVO
                        .getPrimaryKey());
                return materialVO.getPrimaryKey();
            }
            getService().updateMaterial(getUpdateVO(materialVO, pk));
        } catch (Exception ex) {
            Logger.error(ex.getMessage(), ex.getCause());
            throw new BusinessException(ex.getMessage(), ex.getCause());
        }
        return pk;
    }

    private BaseDAO getBaseDAO() {
        if (this.baseDAO == null) {
            this.baseDAO = new BaseDAO();
        }
        return this.baseDAO;
    }

    private MaterialVO getInsertVO(MaterialVO materialVO) throws DAOException {
        materialVO.setEnablestate(Integer.valueOf(2));
        materialVO.setStatus(2);
        materialVO.setMaterialconvert(getMaterialConvertVOs(materialVO));
        materialVO.setMaterialtaxtype(getMaterialTaxTypeVOs(materialVO));
        return materialVO;
    }


    private MaterialConvertVO[] getMaterialConvertVOs(MaterialVO MaterialVO) throws DAOException {
        List<MaterialConvertVO> newConverts = new ArrayList<MaterialConvertVO>();
        if (StringUtils.isNotBlank(MaterialVO.getPrimaryKey())) {
            Collection<MaterialConvertVO> oldAgentStores = getBaseDAO().retrieveByClause(MaterialConvertVO.class, "pk_material = '" + MaterialVO
                    .getPrimaryKey() + "'", new String[]{"pk_materialconvert"});

            for (MaterialConvertVO agentstore : oldAgentStores) {
                agentstore.setStatus(3);
                newConverts.add(agentstore);
            }
        }
        if (MaterialVO.getMaterialconvert() != null) {
            MaterialVO.getMaterialconvert();/*  87 */
            for (MaterialConvertVO agentstore : MaterialVO.getMaterialconvert()) {
                /*  88 */
                agentstore.setStatus(2);
                /*  89 */
                newConverts.add(agentstore);

            }

        }
        return newConverts.toArray(new MaterialConvertVO[0]);
    }

    private MaterialTaxTypeVO[] getMaterialTaxTypeVOs(MaterialVO MaterialVO) throws DAOException {
        List<MaterialTaxTypeVO> newConverts = new ArrayList<MaterialTaxTypeVO>();
        if (StringUtils.isNotBlank(MaterialVO.getPrimaryKey())) {
            Collection<MaterialTaxTypeVO> oldAgentStores = getBaseDAO().retrieveByClause(MaterialTaxTypeVO.class, "pk_material = '" + MaterialVO
                    .getPrimaryKey() + "'", new String[]{"pk_materialtaxtype"});

            for (MaterialTaxTypeVO agentstore : oldAgentStores) {
                agentstore.setStatus(3);
                newConverts.add(agentstore);
            }
        }
        if (MaterialVO.getMaterialtaxtype() != null) {
            MaterialVO.getMaterialtaxtype();/* 107 */
            for (MaterialTaxTypeVO agentstore : MaterialVO.getMaterialtaxtype()) {
                /* 108 */
                agentstore.setStatus(2);
                /* 109 */
                newConverts.add(agentstore);

            }

        }
        return newConverts.toArray(new MaterialTaxTypeVO[0]);
    }

    private IMaterialBaseInfoService getService() {
        if (this.service == null) {
            this.service = NCLocator.getInstance().lookup(IMaterialBaseInfoService.class);
        }
        return this.service;
    }

    private IMeasdocService getIMeasdocService() {
        if (this.iMeasdocService == null) {
            this.iMeasdocService = NCLocator.getInstance().lookup(IMeasdocService.class);
        }
        return this.iMeasdocService;
    }

    private MaterialVO getUpdateVO(MaterialVO materialVO, String pk) throws BusinessException {
        MaterialVO oldVO = (MaterialVO) getBaseDAO().retrieveByPK(MaterialVO.class, pk, new String[]{"creator", "creationtime", "pk_source", "version", "latest", "enablestate"});


        if (oldVO == null) {
            throw new BusinessException(NCLangRes4VoTransl.getNCLangRes().getStrByID("bdpub", "0bdpub0057"));
        }
        //默认数据处理 zb 2024-10-24
        dealFinalParam(materialVO);

        materialVO.setPrimaryKey(pk);
        materialVO.setCreator(oldVO.getCreator());
        materialVO.setCreationtime(oldVO.getCreationtime());
        materialVO.setPk_source(oldVO.getPk_source());
        materialVO.setVersion(oldVO.getVersion());
        materialVO.setLatest(oldVO.getLatest());
        materialVO.setEnablestate(oldVO.getEnablestate());
        materialVO.setStatus(1);
        materialVO.setTs(oldVO.getTs());
        materialVO.setMaterialconvert(getMaterialConvertVOs(materialVO));
        materialVO.setMaterialtaxtype(getMaterialTaxTypeVOs(materialVO));
        return materialVO;
    }

    private MaterialVO insertMaterialVO(MaterialVO materialVO) throws BusinessException {

        //默认数据处理 zb 2024-10-24
        dealFinalParam(materialVO);


        if (StringUtils.isBlank(materialVO.getPk_source())) {
            materialVO = getService().insertMaterial(getInsertVO(materialVO));
        } else {
            ErrLogReturnValue value = getService().createMaterialVersion(materialVO, materialVO.getPk_source());
            if (value.getReturnValue() == null || !value.getReturnValue().getClass().isArray()) {
                return materialVO;
            }
            materialVO = (MaterialVO) ((Object[]) value.getReturnValue())[0];
            LogErrorMessage(value);
        }

        /**
         * 	分配物料到成本域00101 zb 2024-10-24
         */
        //查询分配的成本域主键，默认分配 00101 安吉 0010101
        Collection<CostRegionVO> costRegionVOs = getBaseDAO().retrieveByClause(CostRegionVO.class, "code = '00101'");
        CostRegionVO CostRegionVO = (nc.vo.corg.CostRegionVO) costRegionVOs.toArray()[0];
//			  ErrLogReturnValue errLog = 
        // 分配成本域
        IMaterialAssignService lookup = NCLocator.getInstance().lookup(IMaterialAssignService.class);

        lookup.assignMaterialByPks(new String[]{materialVO.getPk_material()}, new String[]{CostRegionVO.getPk_costregion()}, null);

        return materialVO;
    }

    private void LogErrorMessage(ErrLogReturnValue value) {
        ErrorMsgVO[] vos = value.getErrLogResult().getErrorMsgs();
        if (vos != null && vos.length > 0) {
            String message = NCLangRes4VoTransl.getNCLangRes().getStrByID("10140mag", "010140mag0200", null, new String[]{
                    Integer.toString(value.getTotalNum()),
                    Integer.toString(value.getErrLogResult().getErrorMessagegNum())
            }) + "\n";
            for (int i = 0; i < vos.length; i++) {
                message = message + vos[i].getErrormsg() + "\n";
            }
            Logger.debug(message);
        }
    }

    /**
     * 物料默认数据处理
     *
     * @param materialVO
     */
    private void dealFinalParam(MaterialVO materialVO) {
        // 默认数据处理
        materialVO.setEu_pdprice("2");
        materialVO.setFlag_drug(UFBoolean.FALSE);
        materialVO.setFlag_base(UFBoolean.FALSE);
        materialVO.setFlag_gmp(UFBoolean.FALSE);
        materialVO.setFlag_highrisk(UFBoolean.FALSE);
        materialVO.setFlag_iv(UFBoolean.FALSE);
        materialVO.setFlag_monitor(UFBoolean.FALSE);
        materialVO.setFlag_nuclide(UFBoolean.FALSE);
        materialVO.setFlag_onlycharge(UFBoolean.FALSE);
        materialVO.setFlag_province(UFBoolean.FALSE);
        materialVO.setFlag_quantitypu(UFBoolean.FALSE);
        materialVO.setFlag_reag(UFBoolean.FALSE);
        materialVO.setFlag_refrigeration(UFBoolean.FALSE);
        materialVO.setFlag_rm(UFBoolean.FALSE);
        materialVO.setFlag_rsa(UFBoolean.FALSE);
        materialVO.setFlag_sd(UFBoolean.FALSE);
        materialVO.setFlag_st(UFBoolean.FALSE);
        materialVO.setFlag_tend(UFBoolean.FALSE);
        materialVO.setFlag_tpn(UFBoolean.FALSE);
        materialVO.setFlag_vacc(UFBoolean.FALSE);
        materialVO.setDurable(UFBoolean.FALSE);
        materialVO.setElectronicsale(UFBoolean.FALSE);
        materialVO.setHcxt(UFBoolean.FALSE);
        materialVO.setHighvalue(UFBoolean.FALSE);
        materialVO.setInpurchase(UFBoolean.FALSE);
        materialVO.setImportstr(UFBoolean.FALSE);
        materialVO.setQualitymanflag(UFBoolean.FALSE);
        materialVO.setRetail(UFBoolean.FALSE);
        materialVO.setSerialmanaflag(UFBoolean.FALSE);
        materialVO.setSpecial(UFBoolean.FALSE);
        materialVO.setStoreback(UFBoolean.FALSE);
        materialVO.setWholemanaflag(UFBoolean.FALSE);
        materialVO.setIselectrans(UFBoolean.FALSE);
        materialVO.setIsprimarybarcode(UFBoolean.FALSE);
        materialVO.setIsfeature(UFBoolean.FALSE);
        materialVO.setIselectrans(UFBoolean.FALSE);
        materialVO.setCharge(UFBoolean.FALSE);
        materialVO.setProductfamily(UFBoolean.FALSE);
        if (materialVO.getMaterialconvert() != null) {
            materialVO.getMaterialconvert();
            for (MaterialConvertVO vo : materialVO.getMaterialconvert()) {
                vo.setFlag_ip(UFBoolean.FALSE);
                vo.setFlag_op(UFBoolean.FALSE);

            }
        }
    }

    private HYPubBO pubBO = null;

    private HYPubBO getHYPubBO() {
        if (pubBO == null) {
            pubBO = new HYPubBO();
        }
        return pubBO;
    }
}
